//
//  MTIFileManager.m
//  TP1
//
//  Created by Plopix on 11/06/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "MTIFileManager.h"


@implementation MTIFileManager


+ (NSString *)getPathIn: (ApplicationPath) path {
	NSString *rpath;
	
	switch (path) {
		case (ApplicationPath)APP_TEMP:
			rpath = NSTemporaryDirectory(); 
            break;
		case (ApplicationPath)APP_DOCUMENTS:{
			NSArray *paths;
			paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
			rpath = [paths objectAtIndex:0];
		}
            break;
		default:
			@throw [NSException exceptionWithName:@"MTIFileManager Exception" reason:@"MTIFileManager::getPathIn : path is not authorized" userInfo:nil];
            break;
	}
	return rpath;
}

+ (NSString *) fullPath: (NSString *) fileName In: (ApplicationPath) path {
	return [[MTIFileManager getPathIn:path] stringByAppendingPathComponent:fileName];
}

+ (BOOL)exists: (NSString *) fileName In: (ApplicationPath) path {
	NSFileManager *fileManager = [NSFileManager defaultManager];
	return [fileManager fileExistsAtPath:[MTIFileManager fullPath:fileName In:path]];
}


+ (void) cacheDictionnary: (NSString *) dictName withDict:(NSMutableDictionary*) dict In: (ApplicationPath) path {
	[dict writeToFile:[[MTIFileManager getPathIn:path] stringByAppendingPathComponent:dictName] atomically:YES];
}

+ (NSMutableDictionary *) getCachedDictionnary:(NSString *) dictName In: (ApplicationPath) path {
	if ([MTIFileManager exists:dictName In:path])
		return [NSMutableDictionary dictionaryWithContentsOfFile:[MTIFileManager fullPath:dictName In:path]];
	else return nil;
}

+ (void) cacheImage: (NSString *) imageName withData:(NSMutableData*) data In: (ApplicationPath) path {
	[data writeToFile:[[MTIFileManager getPathIn:path] stringByAppendingPathComponent:imageName] atomically:YES];
}

+ (UIImage *) getCachedImage: (NSString *) imageName In: (ApplicationPath) path {
	if ([MTIFileManager exists:imageName In:path])	
        return [UIImage imageWithContentsOfFile: [MTIFileManager fullPath:imageName In:path]];
	else
		return nil;
}

+ (void) remove: (NSString *) itemName In: (ApplicationPath) path {
	if ([MTIFileManager exists:itemName In:path]) {
		NSFileManager *fileManager = [NSFileManager defaultManager];
		[fileManager removeItemAtPath:[MTIFileManager fullPath:itemName In:path] error:nil];
	}
}

+ (void) rename: (NSString *) sourceName to: (NSString *) destName In: (ApplicationPath) path {
	if ([MTIFileManager exists:sourceName In:path]) {
		NSFileManager *fileManager = [NSFileManager defaultManager];
		[fileManager moveItemAtPath:[MTIFileManager fullPath:sourceName In:path] toPath:[MTIFileManager fullPath:destName In:path] error:nil];
	}
}



@end
